<?php
	class MysqlDb
	{
		private $host;
		private $name;
		private $pass;
		private $dbName;
		private $charset;
		private $link;
		//构造方法是在实例化对象的时候同时执行的方法
		public function __construct($host,$name,$pass,$dbName,$charset){
			$this->host=$host;
			$this->name=$name;
			$this->pass=$pass;
			$this->charset=$charset;
			$this->connect();
			$this->charset();
			$this->changeDb($dbName);

		}

		private function connect(){
			$this->link = mysqli_connect($this->host,$this->name,$this->pass);
		}

		public function changeDb($dbName){
			$this->dbName = $dbName;
			mysqli_select_db($this->link,$this->dbName);
		}

		public function charset(){
			mysqli_set_charset($this->link,$this->charset);
		}

		public function desc($table){
			$sql = "DESC {$table};";
			return $this->getRow($sql);
		}

		public function query($sql){
			return mysqli_query($this->link,$sql);
		}

		public function getOne($sql){
			$r = $this->query($sql);
			if ($r) {
				$row = mysqli_fetch_array($r);
				if(isset($row[0])){
					return $row[0];
				}else{
					return false;
				}
			}
			
		}

		public function getRow($sql){
			$r = $this->query($sql);
			return mysqli_fetch_assoc($r);
		}

		public function getAll($sql){
			$reslut=array();
			$r = $this->query($sql);
			if ($r) {
				while($row=mysqli_fetch_assoc($r)) {
					$reslut[] = $row;
				}
				return $reslut;
			}
			
		}

		public function addRow($table,$row){
			$keys = array_keys($row);
			$key = implode(',', $keys);
			$values = array_values($row);
			$value = implode("','", $values);
			$sql ="INSERT INTO {$table} ({$key}) VALUES ('{$value}')";
			$status = $this->query($sql);
			if($status){
				$sql = "SELECT last_insert_id() as id";
				return $this->getOne($sql);
			}else{
				return false;
			}
		}

		public function addAll($table,$data){
			$keys = array_keys($data[0]);
			$key = implode(',', $keys);
			$sql ="INSERT INTO {$table} ({$key}) VALUES ";
			foreach ($data as $key => $row) {
				$values = array_values($row);
				$value = implode("','", $values);
				$sql=$sql."('{$value}'),";
			}
			$sql = substr($sql, 0,strlen($sql)-1);
			$status = $this->query($sql);
			if($status){
				return true;
			}else{
				return false;
			}
		}

		public function update($table,$row,$condition=''){
			$sql = "UPDATE {$table} SET ";
			foreach ($row as $key => $value) {
				$sql.= "{$key}='{$value}',";
			}
			$sql = substr($sql, 0,strlen($sql)-1);
			if ($condition) {
				$sql=$sql.' WHERE '.$condition;
			}
			$r = $this-> query($sql);
			if ($r) {
				return true;
			}else{
				return false;
			}
		}

		public function del($sql){
			$r = $this-> query($sql);
			if ($r) {
				return true;
			}else{
				return false;
			}
		}
	}